import * as prettier from 'prettier/standalone'
import prettierPluginTypescript from 'prettier/plugins/babel'
import prettierPluginBabel from 'prettier/plugins/estree'

export async function formatCode(
  code: string,
  lang: 'js' | 'ts'
): Promise<string> {
  try {
    return await prettier.format(code, {
      parser: lang === 'ts' ? 'typescript' : 'babel',
      plugins: [prettierPluginTypescript, prettierPluginBabel],
      semi: true,
      singleQuote: true,
      tabWidth: 2
    })
  } catch (e) {
    console.warn('[format] 失败，返回原代码', e)
    return code // 失败就保持原样，不打扰用户
  }
}